package com.tim.ying.zk.consumer;

import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.NotBoundException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ThreadLocalRandom;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import com.tim.ying.zk.util.ZKUtils;

public class ZKServiceConsumer {
	List<String> urlList = new ArrayList<String>();
	
	public ZKServiceConsumer() {
		super();
		ZooKeeper zk = ZKUtils.createServer();
		if(zk!=null){
			watchNode(zk);
		}
		
	}

	public <T extends Remote> T lookup(){
		T service = null;
		int size = urlList.size();
		if(size>0){
			String url;
			if(size==1){
				url = urlList.get(0);
			}else{
				url = urlList.get(ThreadLocalRandom.current().nextInt(size));
			}
			System.out.println("获取到路径为["+url+"]的节点");
			service  = lookupService(url);
		}
		return service;
	}
	
	@SuppressWarnings("unchecked")
	private <T extends Remote> T lookupService(String url){
		try {
			T service = (T) Naming.lookup(url);
			return service;
		} catch (MalformedURLException | RemoteException | NotBoundException e) {
			System.out.println("根据路径获取service错误...");
			e.printStackTrace();
			return null;
		}
	}
	
	private void watchNode(final ZooKeeper zk){
		try {
			List<String> nodeList = zk.getChildren(ZKUtils.ZK_REGISTRY_PATH, new Watcher() {
				
				@Override
				public void process(WatchedEvent event) {
					if(event.getType()==Event.EventType.NodeChildrenChanged){
						watchNode(zk);
					}
				}
			});
			List<String> dataList = new ArrayList<>();
			for(String node:nodeList){
				byte[] data = zk.getData(ZKUtils.ZK_REGISTRY_PATH+"/"+node, false, null);
				dataList.add(new String(data));
				urlList = dataList;
			}
			System.out.println("获取到节点..." + dataList);
		} catch (KeeperException | InterruptedException e) {
			e.printStackTrace();
		}
	}
}
